package frontend;

import java.io.IOException;
import java.util.Date;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import model.Dog;

import db.DogDAO;

/**
 * Servlet implementation class DogService
 */
@WebServlet("/dogservice")
public class DogService extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    Logger logger = Logger.getLogger(DogService.class);

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    @SuppressWarnings("unchecked")
    protected void doGet(HttpServletRequest request,
	    HttpServletResponse response) throws ServletException, IOException {
	PropertyConfigurator.configure("log4j.properties");
	if (request.getParameter("id") != null) {
	    if(request.getParameter("tm") != null){
		Date time = new Date(Long.valueOf(request.getParameter("tm")));
		logger.info("Client request to dogservice at "+time);
	    }
	    try {
		Integer dogNr = new Integer(request.getParameter("id")
			.toString());
		DogDAO dao = new DogDAO();
		Dog d = dao.findById(dogNr);
		if (d == null) {
		    response.getWriter().write("REQUEST_ERROR");
		} else {
		    JSONObject obj = new JSONObject();
		    obj.put("age", d.getAgeInMonths());
		    obj.put("breed", d.getBreed());
		    obj.put("name", d.getName());
		    obj.put("description", d.getDescription());
		    obj.put("id", d.getDogNr());
		    response.setContentType("text/html"); 
		    response.getWriter().write(JSONValue.toJSONString(obj));	   
		}
	    } catch (Exception e) {
		logger.error("Error composing JSON response");
		response.getWriter().write("REQUEST_ERROR");
	    }
	}
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
     *      response)
     */
    protected void doPost(HttpServletRequest request,
	    HttpServletResponse response) throws ServletException, IOException {

    }

}
